package com.tth.learn.addproperties.exec;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author tth
 * @Date 2022/12/1 9:25
 */
public class ThreadPoolTest {
    private static int num = 0;
    public static void main(String[] args) {
        List list1 = new ArrayList();
        for (int i = 0; i < 200; i++) {
            list1.add(i);
        }

        int core = 2;//Runtime.getRuntime().availableProcessors();
        System.out.println("核心线程数："+core+"，最大线程数："+(core*2+1));
        ExecutorService service = new ThreadPoolExecutor(
                core, //核心线程数
                core * 2 + 1,//最大线程数
                3,// 超时多长时间没被调用就会释放
                TimeUnit.SECONDS,// 超时单位
                new ArrayBlockingQueue<>(3),// 阻塞队列
                Executors.defaultThreadFactory(),// 线程工厂，创建线程，一般不用动
                new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的回哪去
        );

        try{
            for (int i = 0; i < 9; i++) {
                // 创建线程
                service.execute(() -> {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 线程池使用完毕，关闭线程池
            service.shutdown();
        }

    }
}
